/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-07 09:26:03
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-11 17:33:46
 * @FilePath: /yt-devops/lib/user_entity_manager.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:convert';

import 'package:native_dart_package/constant/common_strings_constant.dart';
import 'package:native_dart_package/global.dart';
import 'package:native_dart_package/http/event_bus_instance/index.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/model/user_auth.dart';
import 'package:native_dart_package/store/sp_store.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/role_model.dart';
import 'package:yt_devops/model/system_info.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/services/predicates.dart';
import 'package:yt_devops/utils/constants/app_configs.dart';
import 'package:yt_devops/utils/constants/store_keys.dart';
import 'package:yt_devops/utils/func_utils.dart';

import 'components/log_utils.dart';

class UserEntityManager {
  UserEntityManager._();

  static final UserEntityManager _instance = UserEntityManager._();

  static UserEntityManager get instance {
    return _instance;
  }

  UserModel userModel = UserModel();

  SystemInfo systemInfo = AppConfigs.defaultSystemInfo;

  Future<void> getUserInfo() async {
    var userInfo = await SpSotre.instance.getString(StoreKeys.userInfo);
    if (userInfo != null) {
      userModel = UserModel.fromJson(jsonDecode(userInfo));
    }
  }

  List<String> get permission => userModel.appPermissions ?? [];

  List<String> get webPermission => userModel.permissions ?? [];

  Future init() async {
    if (userModel.userId == null) {
      await getInfo();
    }
  }

  factory UserEntityManager() {
    return _instance;
  }

  UserModel load() {
    return userModel;
  }

  Future<void> save(UserModel user) async {
    userModel = user;
    SpSotre.instance.setString(StoreKeys.userInfo, jsonEncode(user.toJson()));
    FuncUtils.changeLocale(lang: userModel.lang);
  }

  Future<void> clean() async {
    userModel = UserModel();
    await SpSotre.instance.remove(
      StoreKeys.userInfo,
    );
  }

  Future cleanAuth() async {
    Global.userAuth = null;
    await SpSotre.instance.remove(CommonStrings.userAuth);
  }

  Future saveAuth(UserAuth auth) async {
    Global.userAuth = auth;
    await SpSotre.instance.setString(CommonStrings.userAuth, auth.toString());
  }

  /// 获取角色id
  int? get roleID {
    List<RoleModel>? roles = userModel.roles;
    // Log.d('isOwner===' + roles.toString());
    int? type = roles != null && roles.isNotEmpty ? roles[0].roleId : null;
    return type;
  }

  Future getInfo() async {
    try {
      var info = await AuthServices().getUserInfo();
      if (info != null) {
        systemInfo = SystemInfo(
            appHome: info['org']?['orgIcon']?['appHome'] ??
                AppConfigs.defaultSystemInfo.appHome,
            appPerson: info['org']?['orgIcon']?['appPerson'] ??
                AppConfigs.defaultSystemInfo.appPerson);
        save(UserModel.fromJson(info));
      }
    } on ApiException catch (e) {
      eventBus.fire(e);
    }
  }
}
